package com.example.demo.service.impl;

import com.example.demo.dto.OrderDTO;
import com.example.demo.dto.OrderDetailDTO;
import com.example.demo.entity.OrdersManagement;
import com.example.demo.mapper.OrdersManagementMapper;
import com.example.demo.service.OrdersManagementService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * <p>
 * 订单管理 服务实现类
 * </p>
 */
@Service
public class OrdersManagementServiceImpl extends ServiceImpl<OrdersManagementMapper, OrdersManagement> implements OrdersManagementService {
    @Autowired
    private OrdersManagementMapper ordersManagementMapper;

    @Autowired
    private UserService userService; // 用户服务

    @Override
    public List<OrderDTO> getBuyerOrdersWithDetails(Integer buyerId) {
        return ordersManagementMapper.selectBuyerOrdersWithDetails(buyerId);
    }

    @Override
    public List<OrderDTO> getSellerOrdersWithDetails(Integer sellerId) {
        return ordersManagementMapper.selectSellerOrdersWithDetails(sellerId);
    }

    @Override
    public OrderDetailDTO getOrderDetailById(Integer orderId) {
        return ordersManagementMapper.selectOrderDetailById(orderId);
    }

    // 取消订单
    @Override
    @Transactional
    public boolean cancelOrder(Integer orderId) {
        OrdersManagement order = getById(orderId);
        if (order == null || !"进行中".equals(order.getOStatus())) {
            return false;
        }

        // 更新订单状态
        baseMapper.cancelOrder(orderId);

        // 更新买家余额
        userService.addBalance(order.getOUserIdTwo(), order.getOTotalAmount());

        // 更新卖家余额
        userService.deductBalance(order.getOUserIdOne(), order.getOTotalAmount());

        return true;
    }

    // 确认收货
    @Override
    public boolean confirmOrder(Integer orderId) {
        OrdersManagement order = getById(orderId);
        if (order == null || !"进行中".equals(order.getOStatus())) {
            return false;
        }
        return baseMapper.confirmOrder(orderId) > 0;
    }

    @Override
    @Transactional
    public String updateOrderStatus(OrdersManagement order) {
        OrdersManagement existingOrder = ordersManagementMapper.selectById(order.getOId());
        if (existingOrder == null) {
            return "订单不存在";
        }

        existingOrder.setOStatus(order.getOStatus());
        ordersManagementMapper.updateById(existingOrder);
        return "订单状态已更新为: " + order.getOStatus();
    }

    @Override
    public OrdersManagement getOrderById(Integer orderId) {
        return ordersManagementMapper.selectById(orderId);
    }
}
